package com.ys.code.generator;

import com.alibaba.druid.pool.DruidDataSource;
import com.ys.code.generator.model.Table;
import com.ys.code.generator.model.TableColumn;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import static com.ys.code.generator.common.Constant.domainName;
import static com.ys.code.generator.common.Constant.packageName;
import static com.ys.code.generator.common.Constant.sourcePath;
import static com.ys.code.generator.common.Constant.targetPath;

/**
 * <p>@description: </p>
 *
 * @author yangshuang
 * @version 1.0
 * @date 2019/8/4 12:02
 */
@Slf4j
public class DtoMain {

    private final static String SQL = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_KEY,COLUMN_COMMENT " +
            "FROM information_schema.COLUMNS " +
            "WHERE TABLE_SCHEMA = 'dmall_wms_pos'" +
            "ORDER BY TABLE_NAME, ORDINAL_POSITION";

    // private static Gson gson = new GsonBuilder().setDateFormat(Constants.DATE_TIME_FORMAT).create();


    public static void main(String[] args)throws Exception  {

        selectTable("vpos_push_config");

    }

    private static void selectTable(String tableInDB) throws Exception {
        Map<String, List<TableColumn>> tableMap = getTableMap();
         List<TableColumn> tableColumns = tableMap.get(tableInDB);

         Table table = new Table();

        table.setTable(tableInDB);
        table.setTableColumns(tableColumns);
        //生成文件
        //写入数据库
        Map<String, Object> map = new HashMap<>();
        //模板
//        map.put("ModelPo.java.vm", "dto/" + domainName + "Po.java");
        map.put("MapperxmlTemplate.xml.vm", "dto/" + domainName + "Mapper.xml");
        for (String templateFile : map.keySet()) {
            String targetFile = (String) map.get(templateFile);
            Properties pro = new Properties();
            pro.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, sourcePath);
            VelocityEngine ve = new VelocityEngine(pro);

            VelocityContext context = new VelocityContext();
            context.put("domainName", domainName);
            context.put("packageName", packageName);
            context.put("table", table);

            Template t = ve.getTemplate(templateFile, "UTF-8");

            File file = new File(targetPath, targetFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            if (!file.exists())
                file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            t.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
            System.out.println("成功生成Java文件:"
                    + (targetPath + targetFile).replaceAll("/", "\\\\"));
        }

    }

    private static Map<String, List<TableColumn>> getTableMap() {
        DruidDataSource dataSource;
        try {
            dataSource = new DruidDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/auto_generate");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            throw new RuntimeException(t);
        }

        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement prepareStatement = connection.prepareStatement(SQL);
            ResultSet resultSet = prepareStatement.executeQuery();

            List<TableColumn> tables = new ArrayList<>();
            while (resultSet.next()) {
                tables.add(new TableColumn(resultSet.getString(1), resultSet.getString(2),
                        resultSet.getString(3), resultSet.getString(4), resultSet.getString(5)));
            }
            return tables.stream().collect(Collectors.groupingBy(TableColumn::getTable));
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

    }

}
